<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
const BRAND = '蔚来';
$db->delete('tDealer', ['sBrand' => BRAND]);
$client = new GuzzleHttp\Client();

$res = $client->get(
    'https://www.nio.cn/nio-house'
);
$html = (string)$res->getBody();
$ok = preg_match('/var nio_places_list_data = \{"places":\[([\s\S]+)?\],"cities"/', $html, $m);



$temp = '[' . str_replace('\'', '"', $m[1]) . ']';
//file_put_contents("a.log",$temp);

//
//$temp = preg_replace(["/([a-zA-Z_]+[a-zA-Z0-9_]*)\s*:/", "/:\s*(['A-Za-z0-9].*['A-Za-z0-9])/"], ['"\1":', ': "\1"'], $temp);
$dealers = json_decode($temp, true);
//$dealers=json_decode(file_get_contents('a.log'), true);
//var_dump($dealers);die;

$cities = json_decode(file_get_contents('cities.json'), true);

$dict = [];
foreach ($cities as $row) {
    foreach ($row['citys'] as $city) {
        $dict[$city['citysName']] = $row['provinceName'];
    }
}

foreach ($dealers as $item) {

    $locat=explode("|", $item['position']);
    
    $db->insert('tDealer', [
        'sDealerName' => $item['title'],
        'nBrandID' => $item['type'],
        'sBrand' => BRAND,
        'sProvince' => $item['province_name'],
        'sCity' => $item['city_name'],
        'sAddress' =>  $item['address'],
        'sSaleCall' => '400-999-6699',
        'sLatitude' => $locat[1],
        'sLongitude' => $locat[0],
        'dUpdateTime' => Medoo::raw('now()'),
        'sManufacturer' => BRAND,
    ]);
    echo "{$item['title']}完成" . PHP_EOL;
}


echo '爬虫结束' . PHP_EOL;